package com.walkline.screen;

import java.io.IOException;
import java.io.OutputStream;

import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;

import localization.WeiboSDKResource;
import net.rim.device.api.i18n.ResourceBundle;
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.system.Characters;
import net.rim.device.api.system.PNGEncodedImage;
import net.rim.device.api.ui.MenuItem;
import net.rim.device.api.ui.component.Menu;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.ui.input.InputSettings;
import net.rim.device.api.ui.input.TouchscreenSettings;
import net.rim.device.api.util.StringProvider;

import com.walkline.util.Enumerations.StorageType;
import com.walkline.util.FileUtility;
import com.walkline.util.Function;
import com.walkline.util.ui.ScrollableImageField;
import com.walkline.weibo.WeiboSDK;

public final class ShowPreivewImageFullScreen extends MainScreen implements WeiboSDKResource
{
	private static ResourceBundle _bundle = ResourceBundle.getBundle(BUNDLE_ID, BUNDLE_NAME);

	private ScrollableImageField _imageField;
	private String _download_uri = StorageType.DEFAULT_URI;
	private String _url = "";
	private Bitmap _image;

    public ShowPreivewImageFullScreen(WeiboSDK weibo, String url, Bitmap bitmap)
    {
        super(NO_VERTICAL_SCROLL | NO_HORIZONTAL_SCROLL | NO_SYSTEM_MENU_ITEMS);

        _download_uri = StorageType.choicesDownloadUri[weibo.getAppConfig().getDownloadLocation()];
        _url = url;
        _image = bitmap;

        _imageField = new ScrollableImageField(bitmap);
        add(_imageField);

        InputSettings inputSettings = TouchscreenSettings.createEmptySet();
        inputSettings.set(TouchscreenSettings.DETECT_PINCH, 1);        
        addInputSettings(inputSettings);            
    }

    private void saveImage()
    {
    	if (!FileUtility.createRecursively(_download_uri))
		{
			Function.errorDialog(getResString(MESSAGE_ERROR_UNABLE_CREATE_FOLDER));
			return;
		}

    	FileConnection file = null;
    	OutputStream output = null;
    	PNGEncodedImage encoder = PNGEncodedImage.encode(_image);

		try {
			file = (FileConnection) Connector.open(_download_uri + FileUtility.getFilename(_url));

			if (!file.exists()) {file.create();}

			file.setWritable(true);

			output = file.openOutputStream();
			output.write(encoder.getData());
			output.flush();
			output.close();

			Function.errorDialog("图片文件已保存!\n\n" + file.getURL());
		} catch (IOException e) {
			Function.errorDialog(e.toString());
		} finally {
			if (file != null) {try {file.close();} catch (IOException e) {}}
			if (output != null) {try {output.close();} catch (IOException e) {}}
		}
    }

    private String getResString(int key) {return _bundle.getString(key);}

    MenuItem menuSaveImage = new MenuItem(new StringProvider("保存图片(S)"), 100, 10)
    {
    	public void run() {saveImage();}
    };

    protected void makeMenu(Menu menu, int instance)
    {
    	menu.add(menuSaveImage);

    	super.makeMenu(menu, instance);
    }

    protected boolean keyChar(char character, int status, int time)
    {
    	switch (character)
    	{
			case Characters.LATIN_CAPITAL_LETTER_S:
			case Characters.LATIN_SMALL_LETTER_S:
				saveImage();
				return true;
			case Characters.LATIN_CAPITAL_LETTER_Q:
			case Characters.LATIN_SMALL_LETTER_Q:
				Function.showExitDialog();
				return true;
		}

    	return super.keyChar(character, status, time);
    }

    /*
    protected boolean touchEvent(TouchEvent message)
    {
        if (message.getEvent() == TouchEvent.GESTURE)
        {
            TouchGesture gesture = message.getGesture();
            int event = gesture.getEvent();

            float magnitude = gesture.getPinchMagnitude();

            if (event == TouchGesture.PINCH_UPDATE)
            {
                onPinch(magnitude, false);                                                    
            } else if(event == TouchGesture.PINCH_END) {                   
                onPinch(magnitude, true);
            }
        }

        return super.touchEvent(message);
    }

    private void onPinch(float magnitude, boolean pinchEnd)
    {                 
        // Calculate dimensions, restrict to screen size        
        float width = Math.min(_previousWidth * magnitude, (float)Display.getWidth());
        float height = Math.min(_previousHeight * magnitude, (float)Display.getHeight());

        // Maintain aspect ratio when either width or height is maxed out        
        if (width == (float)Display.getWidth() || height == (float)Display.getHeight())
        {
            float ratioWidth = 1f;
            float ratioHeight = 1f;

            ratioWidth = width / _previousWidth;
            ratioHeight = height / _previousHeight;

            if (ratioWidth < ratioHeight)
            {
                height = _previousHeight * ratioWidth;
            } else if(ratioHeight < ratioWidth) {
                width = _previousWidth * ratioHeight;
            }
        }

        // Ensure Bitmap will be at least original size
        width = Math.max(width, _origWidth);
        height = Math.max(height, _origHeight);

        // Create Bitmap from original scaled to new calculated dimensions
        Bitmap bitmapScaled = new Bitmap((int)width, (int)height);
        _bitmapOrig.scaleInto(bitmapScaled, Bitmap.FILTER_BOX);

        // Replace Bitmap
        _imageField.setBitmap(bitmapScaled);

        // Save current dimensions
        if(pinchEnd)
        {
            _previousWidth = width;
            _previousHeight = height;
        }
    }

    private final class DemoBitmapField extends BitmapField
    {
        DemoBitmapField(Bitmap bitmap, long style) {super(bitmap, style);}

        protected void layout(int width, int height)
        {       
            float displayWidth = (float)Display.getWidth();
            float displayHeight = (float)Display.getHeight();

            float newWidth = (float)width;
            float newHeight = (float)height;

            if (displayWidth < _previousWidth  || displayHeight < _previousHeight)
            {                
                float ratioWidth = 1;
                float ratioHeight = 1;

                ratioWidth = displayWidth / _previousWidth;
                ratioHeight = displayHeight / _previousHeight;

                if (ratioWidth < ratioHeight)
                {
                    newHeight = _previousHeight * ratioWidth;
                } else if(ratioHeight < ratioWidth) {
                    newWidth = _previousWidth * ratioHeight;
                }

                // Create Bitmap from original scaled to new calculated dimensions
                final Bitmap bitmapScaled = new Bitmap((int)newWidth, (int)newHeight);
                _bitmapOrig.scaleInto(bitmapScaled, Bitmap.FILTER_BOX);

                // Need to use invokeLater() as bitmap cannot be set while in layout().
                UiApplication.getUiApplication().invokeLater(new Runnable()
                {
                   public void run() {_bitmapField.setBitmap(bitmapScaled);} 
                });                                   

                _previousWidth = (float)newWidth;
                _previousHeight = (float)newHeight;
            }

            setExtent((int)newWidth, (int)newHeight);

            super.layout((int)newWidth, (int)newHeight);
        }
    }
    */
}